package org.hcyspartnoc.demo.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import org.aspectj.weaver.loadtime.Aj;
import org.hcyspartnoc.demo.common.core.AjaxResult;
import org.hcyspartnoc.demo.common.core.PageBean;
import org.hcyspartnoc.demo.common.core.annotation.Log;
import org.hcyspartnoc.demo.common.core.annotation.PreAuthorize;
import org.hcyspartnoc.demo.common.core.enums.BusinessType;
import org.hcyspartnoc.demo.common.exception.common.CommonUtilsException;
import org.hcyspartnoc.demo.common.exception.framework.AuthException;
import org.hcyspartnoc.demo.common.exception.system.SysRoleException;
import org.hcyspartnoc.demo.common.exception.system.SysUserException;
import org.hcyspartnoc.demo.pojo.dto.system.*;
import org.hcyspartnoc.demo.pojo.po.system.SysRolePo;
import org.hcyspartnoc.demo.pojo.po.system.SysUserPo;
import org.hcyspartnoc.demo.pojo.vo.system.SysUserPageDataVo;
import org.hcyspartnoc.demo.pojo.vo.system.SysUserVo;
import org.hcyspartnoc.demo.service.system.impl.SysRoleServiceImpl;
import org.hcyspartnoc.demo.service.system.impl.SysUserServiceImpl;
import org.hibernate.validator.constraints.Length;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping
public class SysUserController {
    @Resource
    private SysUserServiceImpl sysUserService;

    @Resource
    private SysRoleServiceImpl sysRoleService;


    @Log(title = "系统·用户·登录·账号", businessType = BusinessType.OTHER, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:login:account", descr = "通过账号密码登录")
    @PostMapping("/sys/user/login/account")
    public AjaxResult loginByAccount(@Valid @RequestBody SysUserLoginByPhoneDto sysUserLoginByPhoneDto) throws SysUserException, CommonUtilsException {
        SysUserVo userVo = sysUserService.loginByAccount(sysUserLoginByPhoneDto);
        return AjaxResult.success(userVo);
    }

    @Log(title = "系统·用户·修改·头像", businessType = BusinessType.UPDATE, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:modify:avatar", descr = "用户修改头像")
    @PutMapping("/modify/avatar")
    public AjaxResult modifyAvatar(@NotNull @RequestParam MultipartFile image) throws CommonUtilsException, SysUserException {
        String resultURL = sysUserService.modifyAvatar(image);
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("url", resultURL);
        return AjaxResult.success(resultMap);
    }

    @Log(title = "系统·用户·修改·密码", businessType = BusinessType.UPDATE, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:modify:pwd", descr = "用户修改密码")
    @PutMapping("/modify/pwd")
    public AjaxResult modifyPassword(@Valid @RequestBody SysUserModifyPwdDto sysUserModifyPwdDto) throws SysUserException {
        sysUserService.modifyPassword(sysUserModifyPwdDto);
        return AjaxResult.successMsg();
    }

    @Log(title = "系统·用户·修改·基础信息", businessType = BusinessType.UPDATE, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:modify:baseInfo", descr = "用户修改基础信息")
    @PutMapping("/modify/baseInfo")
    public AjaxResult modifyBaseInfo(@Valid @RequestBody SysUserModifyBaseInfoDto sysUserModifyBaseInfoDto) {
        sysUserService.modifyBaseInfo(sysUserModifyBaseInfoDto);
        return AjaxResult.successMsg();
    }

    @Log(title = "系统·用户·查询·通过token", businessType = BusinessType.OTHER)
    @PreAuthorize(auth = "system:user:query:token", descr = "通过token获取用户信息")
    @GetMapping("/query/token")
    public AjaxResult queryByToken() {
        SysUserVo sysUserVo = sysUserService.queryByToken();
        return AjaxResult.success(sysUserVo);
    }

    @Log(title = "系统·用户·换绑·角色", businessType = BusinessType.UPDATE, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:rebinding:role", descr = "换绑用户角色")
    @PutMapping("/rebinding/role")
    public AjaxResult rebindingRole(@Valid @RequestBody SysUserRebindingRoleDto sysUserRebindingRoleDto) throws SysUserException, SysRoleException {
        sysUserService.rebindingRole(sysUserRebindingRoleDto);
        return AjaxResult.successMsg();
    }

    @Log(title = "系统·用户·修改·状态", businessType = BusinessType.UPDATE, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:modify:status", descr = "修改用户状态")
    @PutMapping("/modify/status")
    public AjaxResult modifyStatus(@Valid @RequestBody SysUserModifyStatusDto sysUserModifyStatusDto) throws SysUserException, AuthException, SysRoleException {
        sysUserService.modifyStatus(sysUserModifyStatusDto);
        return AjaxResult.successMsg();
    }

    @Log(title = "系统·用户·查询·分页", businessType = BusinessType.OTHER, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:query:page", descr = "分页查询用户")
    @PostMapping("/admin/user/user/list")
    public AjaxResult queryPage(@RequestBody SysuserPageDto sysuserPageDto) {
        int currentPage=sysuserPageDto.getCurrent();
        int pageSize=sysuserPageDto.getPageSize();
        String  nickname=sysuserPageDto.getNickname();
        String account=sysuserPageDto.getAccount();
        List<Integer> roleIds=sysuserPageDto.getRoleIds();
        String sortField=sysuserPageDto.getSortField();
        String sortFiedl=sysuserPageDto.getSortOrder();
        PageBean<SysUserPo, SysUserVo> sysUserPoSysUserVoPageBean = sysUserService.queryPage(currentPage, pageSize, nickname, account, roleIds, sortField, sortFiedl);
        List<SysUserVo> records = sysUserPoSysUserVoPageBean.getList();
        long total = sysUserPoSysUserVoPageBean.getTotal();
        SysUserPageDataVo data = new SysUserPageDataVo(records, total);
        return AjaxResult.success(data);
    }

    @Log(title = "系统·用户·注销", businessType = BusinessType.DELETE, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:logout", descr = "注销用户")
    @DeleteMapping("/logout")
    public AjaxResult logout() throws SysUserException {
        sysUserService.logout();
        return AjaxResult.successMsg();
    }

    @Log(title = "系统·用户·编辑", businessType = BusinessType.DELETE, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:updateAndadd", descr = "编辑用户")
    @PostMapping("/admin/user/user/save")
    public AjaxResult updateAndadd(@Valid @RequestBody SysUserUpdateAndAddDto sysUserUpdateAndAddDto) {
        boolean result = sysUserService.updateUser(sysUserUpdateAndAddDto);
        return result ? AjaxResult.success("操作成功") : AjaxResult.error("操作失败");
    }

    @Log(title = "系统·用户·账号是否存在", businessType = BusinessType.DELETE, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:account", descr = "账号是否存在")
    @PostMapping("/admin/user/user/checkAccount")
    public AjaxResult checkaccount(@RequestBody SysUserDao sysUserDao) {
        QueryWrapper<SysUserPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", sysUserDao.getAccount());
        boolean exists = sysUserService.exists(queryWrapper);
        return exists==true?AjaxResult.error(false):AjaxResult.success();
    }
    @Log(title = "系统·用户·新增", businessType = BusinessType.INSERT, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:register:wx", descr = "通过微信注册用户")
    @PostMapping("/admin/user/user/add")
    public AjaxResult useradd(@RequestBody SysUserAddDto sysUserAddDto) throws SysUserException {
        if (sysUserAddDto==null){
           throw  new SysUserException("注册信息不全");
        }
        sysUserService.addNewUser(sysUserAddDto);
        return AjaxResult.success();
    }
    @Log(title = "系统·用户·删除", businessType = BusinessType.INSERT, isSaveResponseData = false)
    @PreAuthorize(auth = "system:user:delete", descr = "删除用户")
    @PostMapping("/admin/user/user/delete")
    public AjaxResult userDelete(@RequestBody SysUserdeleteDto sysUserdeleteDto){
        String[] userIds = sysUserdeleteDto.getIds().split(",");
        for (String userid :userIds)
        {
            Integer user= Integer.parseInt(userid);
            sysUserService.removeuserByid(user);
        }
        return AjaxResult.successMsg();
    }
}
